package com.app.twth.ui.b2btrailer.oblpn;


import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityB2bTrailerOblpnBinding;
import com.app.twth.databinding.DialogB2bTrailerBinding;
import com.app.twth.databinding.DialogOutboundRemoveTrackingBinding;
import com.app.twth.ui.b2btrailer.B2BTrailerViewModel;
import com.app.twth.ui.b2btrailer.submit.B2BTrailerSubmitActivity;
import com.app.twth.ui.b2btrailer.submit.B2bTrailerQr;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @describe :
 */
public class B2BTrailerOBLPNActivity extends BaseActivity<ActivityB2bTrailerOblpnBinding, B2BTrailerViewModel> {
    private String TAG = getClass().getSimpleName();
    private List<B2BTrailerLpn> dataList = new ArrayList<>();
    private B2BTrailerOBLPNAdapter adapter;

    @Override
    protected void initListener() {

        viewModel.loadedObLpnLiveData.observe(this, data -> {
            binding.tvOblpnList.setText("OBLPN List(" + data.size() + ")");
            dataList.clear();
            dataList.addAll(data);
            adapter.notifyDataSetChanged();
        });
        viewModel.pendingObLpnLiveData.observe(this, data -> {
            if (data == null || data.size() == 0) {
                return;
            }
            showPendinglDialog(data);
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "B2BTrailer(OBLPN)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        viewModel.b2bTrailerQrLiveData.setValue((B2bTrailerQr) bundle.getSerializable("B2bTrailerQr"));

        binding.tvTrailer.setText("(" + viewModel.b2bTrailerQrLiveData.getValue().getRefId() + ")" + viewModel.b2bTrailerQrLiveData.getValue().getOrderNo());

        setNext("");
        binding.tvCode.requestFocus();
        binding.tvCode.setOnEditorActionListener(EnterListenter);

        adapter = new B2BTrailerOBLPNAdapter(this, dataList, position -> {
            if (System.currentTimeMillis() - timeMillis < 500) {//两秒内触发一次
                return;
            }
            timeMillis = System.currentTimeMillis();
            showRemoveTrackingDialog(position);
        });
        LinearLayoutManager oblpnLayoutManager = new LinearLayoutManager(this);
        oblpnLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvOblpn.setLayoutManager(oblpnLayoutManager);
        binding.rvOblpn.setAdapter(adapter);
        viewModel.b2bTrailerLoadedObLpn();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                setScan();
                break;
            case R.id.tv_reset:
                clearData();
                break;
            case R.id.layout_trailer:
                viewModel.b2bTrailerPendingObLpn();
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                setNext();
                break;
        }
    }

    private void clearData() {
        binding.tvCode.setText("");
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                EditTextUtil.hideInput(mContext);
            }
            //关闭软键盘
            EditTextUtil.hideInput(mContext);
            if (!Utils.isEmpty(barcodeStr)) {
                setCheckLpn(barcodeStr);
            }
            return false;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.ForResult2:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getBundleExtra(AppRouter.K_EXTRA);
                    boolean isFilish = bundle.getBoolean("isFilish");
                    if (isFilish) {
                        Intent intent = new Intent();
                        setResult(RESULT_OK, intent);
                        finish();
                        return;
                    }
                    clearData();
                    viewModel.b2bTrailerLoadedObLpn();
                }
                break;
        }
    }

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        binding.tvCode.setText(barcodeStr);
        setCheckLpn(barcodeStr);
    }

    private void setCheckLpn(String barcodeStr) {
        if (viewModel.loadedObLpnLiveData.getValue() != null) {
            for (B2BTrailerLpn trailerOBLPN : viewModel.loadedObLpnLiveData.getValue()) {
                if (trailerOBLPN.getObLpn().equals(barcodeStr)) {
                    return;
                }
            }
        }
        viewModel.b2bTrailerCheckObLpn(barcodeStr);
    }

    private AlertDialog dialogRemoveTracking;

    private void showRemoveTrackingDialog(int position) {
        dialogRemoveTracking = MyDialogUtil.getDialog(mContext, initRemoveTrackingDialogView(position), Gravity.CENTER);
        dialogRemoveTracking.setCanceledOnTouchOutside(false);
        dialogRemoveTracking.show();
    }

    private View initRemoveTrackingDialogView(int position) {
        B2BTrailerLpn trailerOBLPN = viewModel.loadedObLpnLiveData.getValue().get(position);
        DialogOutboundRemoveTrackingBinding dialogBinding = DialogOutboundRemoveTrackingBinding.inflate(getLayoutInflater());
        dialogBinding.tvContent.setText("Remove " + trailerOBLPN.getObLpn() + " form " + viewModel.b2bTrailerQrLiveData.getValue().getOrderNo());
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogRemoveTracking != null) {
                dialogRemoveTracking.dismiss();
            }
        });
        dialogBinding.tvConfirm.setOnClickListener(v -> {
            if (dialogRemoveTracking != null) {
                dialogRemoveTracking.dismiss();
            }
            if (trailerOBLPN.getDetailId() == null) {
                viewModel.loadedObLpnLiveData.getValue().remove(position);
                viewModel.loadedObLpnLiveData.setValue(viewModel.loadedObLpnLiveData.getValue());
                return;
            }
            viewModel.b2bTrailerRemove(position, trailerOBLPN.getDetailId());

        });
        return dialogBinding.getRoot();
    }

    private void setNext() {
        if ((viewModel.loadedObLpnLiveData.getValue() == null) || (viewModel.loadedObLpnLiveData.getValue().size() == 0)) {
            showHint("Please add OUTBOUND LPN");
            return;
        }
        List<String> lpns = new ArrayList<>();
        lpns.clear();
        for (B2BTrailerLpn trailerOBLPN : viewModel.loadedObLpnLiveData.getValue()) {
//            if (trailerOBLPN.getDetailId() == null) {
                lpns.add(trailerOBLPN.getObLpn());
//            }
        }
        if (lpns.size() == 0) {
            showHint("Please add OUTBOUND LPN");
            return;
        }
        viewModel.b2bTrailerQrLiveData.getValue().setObLpnList(lpns);
        Bundle bundle = new Bundle();
        bundle.putSerializable("B2bTrailerQr", viewModel.b2bTrailerQrLiveData.getValue());
        AppRouter.showActivityForResult(mContext, B2BTrailerSubmitActivity.class, bundle, Constant.ForResult2);
    }

    private AlertDialog pendingDialog;

    private void showPendinglDialog(List<B2BTrailerLpn> pendingDatas) {
        pendingDialog = MyDialogUtil.getDialog(mContext, initPendingDialogView(pendingDatas), Gravity.CENTER);
        pendingDialog.setCanceledOnTouchOutside(true);
        pendingDialog.show();
    }

    private View initPendingDialogView(List<B2BTrailerLpn> pendingDatas) {
        DialogB2bTrailerBinding dialogBinding = DialogB2bTrailerBinding.inflate(getLayoutInflater());

        dialogBinding.tvTitle.setText("Pending OBLPN(" + pendingDatas.size() + ")");
        B2BTrailerPendingLpnAdapter pendingLpnAdapter = new B2BTrailerPendingLpnAdapter(this, pendingDatas);

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerview.setLayoutManager(layoutManager1);
        dialogBinding.recyclerview.setAdapter(pendingLpnAdapter);

        dialogBinding.tvTitle.setOnClickListener(v -> {
            if (pendingDialog != null) {
                pendingDialog.dismiss();
            }
        });
        return dialogBinding.getRoot();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
